//
//  HXbluetoothLinkStyleCell.m
//  HongxuanBluetooth
//
//  Created by 广州弘轩科技发展有限公司 on 2023/8/2.
//

#import "HXbluetoothLinkStyleCell.h"

@implementation HXbluetoothLinkStyleCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self initSubview];
    }
    return self;
}
- (void)initSubview{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(bluetoothTime:) name:@"bluetoothTime" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changelanguages) name:@"changelanguages" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:NOTIFICATION_MESSAGE_NAME object:nil];

//    self.contentView.backgroundColor = [UIColor blackColor];
    
//    self.blueToothManager = [BlueToothManager shareInstance];
    
    
    self.isxianshi = YES;
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.bounds.size.width, 200)];
//        imgView = [[UIImageView alloc] initWithFrame:CGRectMake(30, 0, 234.75, 230)];
    self.imgView.tag = kViewTag;
//    self.imgView.backgroundColor = [UIColor greenColor];
    [self.contentView addSubview:self.imgView];
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 8;
    UILabel *time = [[UILabel alloc] init];
    time.text = @"timetime ";
    time.textColor = [UIColor redColor];
    [self.contentView addSubview: time];
    
    
    UIImageView *bjview = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
    self.bjview = bjview;
    if([themeColors isEqualToString:@"default"]){
        self.contentView.backgroundColor = [UIColor blackColor];
        bjview.image = [UIImage imageNamed:@"linkbackground"];
        bjview.backgroundColor = [UIColor blackColor];
        
        self.textView.backgroundColor = [UIColor blackColor];
        
    }else{
        self.contentView.backgroundColor = midnightRGB;
        bjview.image = [UIImage imageNamed:@""];
        bjview.backgroundColor = midnightRGB;
        self.textView.backgroundColor = midnightRGB;
    }
    
    bjview.userInteractionEnabled = YES;
    [self.contentView addSubview:bjview];
    
    UIImageView *linklogo = [[UIImageView alloc] initWithFrame:CGRectMake(25, 40, 29, 36)];
    linklogo.image = [UIImage imageNamed:@"linklogo1"];
    _linklogo = linklogo;
    [bjview addSubview:linklogo];
    
#pragma mark - 手表显示 deviceicon  画板显示 brush
    UIImageView *deviceiconview = [[UIImageView alloc] initWithFrame:CGRectMake(88, 40, 36, 36)];
    deviceiconview.image = [UIImage imageNamed:@"deviceicon"];
    [bjview addSubview:deviceiconview];
    _deviceiconview = deviceiconview;
    
//    brush
    UIImageView *brushview = [[UIImageView alloc] initWithFrame:CGRectMake(88, 40, 34.33, 36)];
    brushview.image = [UIImage imageNamed:@"brush"];
    [bjview addSubview:brushview];
    _brushview = brushview;
    

    

//    _equipmentname =[[UILabel alloc] init];
//    _equipmentname.text = @"xxxxxxxxx";
//    _equipmentname.font = [UIFont systemFontOfSize:18];
//    _equipmentname.textColor = [UIColor whiteColor];
//    [bjview addSubview:_equipmentname];
//    [_equipmentname mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(deviceiconview.mas_right).offset(5);
//        make.centerY.mas_equalTo(_deviceiconview.mas_centerY);
//        make.height.mas_equalTo(30);
//        make.width.mas_equalTo(150);
//
//    }];
//
    self.textView = [[UITextView alloc]init];
    [bjview addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(deviceiconview.mas_right).offset(5);
        make.centerY.mas_equalTo(_deviceiconview.mas_centerY);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(150);
    }];
    self.textView.delegate = self;
    
    //修复文本框是偏移（下移）
//    self.automaticallyAdjustsScrollViewInsets = NO;
    
//    self.textView.backgroundColor = [UIColor blackColor];
    if([themeColors isEqualToString:@"default"]){
        
        self.textView.backgroundColor = [UIColor blackColor];
    }else{
        
        self.textView.backgroundColor = midnightRGB;
    }
    //设置文本
//    self.textView.text = @"我是UITextView，大家欢迎使用。";
    //设置文字对齐方式属性
    self.textView.textAlignment = NSTextAlignmentLeft;
    //设置文字对齐方
    //设置文字颜色属性
    self.textView.textColor = [UIColor whiteColor];
    //设置文字字体属性
    self.textView.font = [UIFont systemFontOfSize:16.0f];
    //设置编辑使能属性,是否允许编辑（=NO时，只用来显示，依然可以使用选择和拷贝功能）
    self.textView.editable = YES;
    
    self.textView.keyboardType = UIKeyboardTypeEmailAddress;
    
    
    _attributeentryview = [[UIImageView alloc] init];
    _attributeentryview.image = [UIImage imageNamed:@"attributeentry"];
    _attributeentryview.userInteractionEnabled = YES;
    [bjview addSubview:_attributeentryview];
    [_attributeentryview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(46);
        make.right.mas_equalTo(-25);
        make.width.height.mas_equalTo(25);
    }];
    
    UIButton *buteentrybt = [UIButton buttonWithType:UIButtonTypeCustom];
    [buteentrybt addTarget:self action:@selector(editStatusbt) forControlEvents:UIControlEventTouchUpInside];
    [bjview addSubview:buteentrybt];
    [buteentrybt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(46);
        make.right.mas_equalTo(-25);
        make.width.height.mas_equalTo(25);
    }];
    
    
    UIImageView *line = [[UIImageView alloc] init];
    line.image = [UIImage imageNamed:@"honeline"];
    [bjview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(115);
    }];
    
    
#pragma make 手表就显示时间/蓝牙设置的时间。 写字板显示笔画
    
    UILabel *timelb = [[UILabel alloc] init];
    timelb.font = [UIFont systemFontOfSize:90];
    
    NSString *bluetoothTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"Bluetoothtime"];
    NSLog(@"bluetoothTime :%@",bluetoothTime);
    if(bluetoothTime.length>0){
        timelb.text = bluetoothTime;
    }else{
        timelb.text = @"00:00";
    }
//    timelb.text = @"00:00";
    timelb.textColor = [UIColor whiteColor];
    timelb.textAlignment = NSTextAlignmentCenter;
    [bjview addSubview:timelb];
    
    _timelb = timelb;
    [timelb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(37);
        make.right.mas_equalTo(-37);
        make.top.mas_equalTo(line.mas_bottom).offset(71);
        make.height.mas_equalTo(68);
        make.centerX.mas_equalTo(self.contentView);
    }];
#pragma mark 写字板就显示笔画
    UIImageView *strokesview = [[UIImageView alloc] init];
    strokesview.image = [UIImage imageNamed:@"strokes"];
    [bjview addSubview:strokesview];
    _strokesview = strokesview;
    
    NSLog(@"strokesview 隐藏了1");
    [strokesview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(31);
        make.top.mas_equalTo(line.mas_bottom).offset(66);
        make.right.mas_equalTo(-31);
        make.height.mas_equalTo(80.33);
    } ];
    NSLog(@"选中的下标 %d",_dissindex);
    
    
    UIImageView *linebottom = [[UIImageView alloc] init];
    linebottom.image = [UIImage imageNamed:@"honeline"];
    [bjview addSubview:linebottom];
    [linebottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(403);
    }];
    
//    fullsignal 信号
    
    UIImageView *fullsignalview = [[UIImageView alloc] init];
    fullsignalview.image = [UIImage imageNamed:@"signalmian"];
    [bjview addSubview:fullsignalview];
    [fullsignalview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_bottom).offset(27);
        make.left.mas_equalTo(40);
        make.width.mas_equalTo(49);
        make.height.mas_equalTo(24.33);
    }];
//    self.blueToothManager = [BlueToothManager shareInstance];
////    暂时定位信号值
//    
//    self.blueToothManager.RSSIBlock = ^(NSInteger rsii) {
//        if(rsii>=-50){
////            NSLog(@"信号0 -- -50");
//            fullsignalview.image = [UIImage imageNamed:@"signalmian"];
//        }
//        if(rsii< -50&&rsii>=-60){
////            NSLog(@"信号-50 -- -60");
//            fullsignalview.image = [UIImage imageNamed:@"signalmian3"];
//        }
//        if(rsii< -60&&rsii>-70){
////            NSLog(@"信号-60 -- -70");
//            fullsignalview.image = [UIImage imageNamed:@"signalmian2"];
//        }
//        if(rsii<= -70&&rsii>-80){
////            NSLog(@"信号-60 -- -70");
//            fullsignalview.image = [UIImage imageNamed:@"signalmian1"];
//        }
//        if(rsii<= -80){
////            NSLog(@"信号-80以上");
//            fullsignalview.image = [UIImage imageNamed:@"signalmian0"];
//        }
////        timelb.text = [NSString stringWithFormat:@"%ld",rsii];
//        
//    };
    UILabel *realtime = [[UILabel alloc] init];
    realtime.text = @"00:00";
    realtime.font = [UIFont systemFontOfSize:20];
    realtime.textColor = [UIColor whiteColor];
    realtime.textAlignment = NSTextAlignmentCenter;
    [bjview addSubview:realtime];
    _realtime = realtime;
    [realtime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_bottom).offset(33);
        make.width.mas_equalTo(62);
        make.height.mas_equalTo(18);
        make.centerX.mas_equalTo(self.contentView);
    }];
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(gaintime) userInfo:nil repeats:YES];
   //手写代码，加入runLoop
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

    
//    [self gaintime];
    
//    电量 batterystatus
    UIImageView *batterystatus = [[UIImageView alloc] init];
    batterystatus.image = [UIImage imageNamed:@"batterystatus"];
    self.batterystatus = batterystatus;
    [bjview addSubview:batterystatus];
    [batterystatus mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(line.mas_bottom).offset(27);
        make.right.mas_equalTo(-40);
        make.width.mas_equalTo(43.67);
        make.height.mas_equalTo(23.67);
    }];
    
    WeakSelf
    self.blueToothManager = [BlueToothManager shareInstance];
    
//    [self lastTimeOfThedevice];//获取之前最后的时间
    
    
    
    
//    暂时定位信号值
    static int dian = 0;
    self.blueToothManager.RSSIBlock = ^(NSInteger rsii) {
        dian ++;
        if(rsii>=-50){
//            NSLog(@"信号0 -- -50");
            fullsignalview.image = [UIImage imageNamed:@"signalmian"];
        }
        if(rsii< -50&&rsii>=-60){
//            NSLog(@"信号-50 -- -60");
            fullsignalview.image = [UIImage imageNamed:@"signalmian3"];
        }
        if(rsii< -60&&rsii>-70){
//            NSLog(@"信号-60 -- -70");
            fullsignalview.image = [UIImage imageNamed:@"signalmian2"];
        }
        if(rsii<= -70&&rsii>-80){
//            NSLog(@"信号-60 -- -70");
            fullsignalview.image = [UIImage imageNamed:@"signalmian1"];
        }
        if(rsii<= -80){
//            NSLog(@"信号-80以上");
            fullsignalview.image = [UIImage imageNamed:@"signalmian0"];
        }
//        timelb.text = [NSString stringWithFormat:@"%ld",rsii];
//        NSLog(@"获取电量时间 ：%ld",dian);
        if(dian % 60 == 0){
            NSLog(@"第一分钟查询电量");
            [weakSelf dianliang];
        }
//        if(weakSelf.blueToothManager.connectionState){
//            NSLog(@"链接状态");
//        }
    };
    [self huoqushijian];
    self.blueToothManager.ConnectionFailureBlock = ^(NSString * _Nonnull uuid) {
        [weakSelf.blueToothManager StartScan];//打开蓝牙
        NSLog(@"设备断开了cell cell  cell");
        timelb.text = @"--:--";
        [[NSNotificationCenter defaultCenter]postNotificationName:@"bluetoothDisconnect" object:nil userInfo:@{@"uuid":uuid}];
    };
    self.blueToothManager.successfulConnectionBlock = ^(NSMutableArray * _Nonnull list) {
      
        NSLog(@"cell cell 链接成功：%@",list);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"linkSuccess" object:nil userInfo:@{@"list":list}];
    };
    
//    tutoria 教程
    UIImageView *tutorialview = [[UIImageView alloc] init];
    tutorialview.image = [UIImage imageNamed:@"tutoria"];
    tutorialview.userInteractionEnabled = YES;
    [bjview addSubview:tutorialview];
    [tutorialview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(linebottom.mas_bottom).offset(-37.33);
        make.left.mas_equalTo(45.67);
        make.width.mas_equalTo(54.33);
        make.height.mas_equalTo(58.33);
    }];
//tutoria 跳转教程
    UIButton *tutoriajumpbt = [UIButton buttonWithType:UIButtonTypeSystem];
//    tutoriajumpbt.backgroundColor = [UIColor greenColor];
    [tutorialview addSubview:tutoriajumpbt];
    [tutoriajumpbt addTarget:self action:@selector(tutoriajumpbt) forControlEvents:UIControlEventTouchUpInside];
    [tutoriajumpbt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.width.mas_equalTo(54.33);
        make.height.mas_equalTo(58.33);
        
    }];

#pragma mark - 手表显示 reset  画板显示erase
//    reset
    UIImageView *resetview = [[UIImageView alloc] init];
    resetview.image = [UIImage imageNamed:@"reset"];
    resetview.userInteractionEnabled = YES;

    [bjview addSubview:resetview];
    _resetview = resetview;
    [resetview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(linebottom.mas_bottom).offset(-37.33);
        make.centerX.mas_equalTo(bjview);
        make.width.mas_equalTo(38.33);
        make.height.mas_equalTo(58.33);
    }];
    
    UIButton *resetjumpbt = [UIButton buttonWithType:UIButtonTypeSystem];
//    tutoriajumpbt.backgroundColor = [UIColor greenColor];
    [resetview addSubview:resetjumpbt];
    [resetjumpbt addTarget:self action:@selector(resetjumpbt) forControlEvents:UIControlEventTouchUpInside];
    [resetjumpbt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(resetview);

    }];
    
//    erase
    UIImageView *eraseview = [[UIImageView alloc] init];
    eraseview.image = [UIImage imageNamed:@"erase"];
    eraseview.userInteractionEnabled = YES;
    
    [bjview addSubview:eraseview];
    _eraseview = eraseview;
    [eraseview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(linebottom.mas_bottom).offset(-37.33);
        make.centerX.mas_equalTo(bjview);
        make.width.mas_equalTo(42.67);
        make.height.mas_equalTo(58.33);
    }];
    
    UIButton *erasejumpbt = [UIButton buttonWithType:UIButtonTypeSystem];
//    tutoriajumpbt.backgroundColor = [UIColor greenColor];
    [eraseview addSubview:erasejumpbt];
    [erasejumpbt addTarget:self action:@selector(erasejumpbt) forControlEvents:UIControlEventTouchUpInside];
    [erasejumpbt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(eraseview);

    }];
    
    
    
//    detail
    UIImageView *detailview = [[UIImageView alloc] init];
    detailview.image = [UIImage imageNamed:@"detail"];
    detailview.userInteractionEnabled = YES;
    [bjview addSubview:detailview];
    [detailview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(linebottom.mas_bottom).offset(-37.33);
        make.right.mas_equalTo(-45.67);
        make.width.mas_equalTo(40.33);
        make.height.mas_equalTo(54.33);
    }];
    
    UIButton *detailjumpbt = [UIButton buttonWithType:UIButtonTypeSystem];
//    tutoriajumpbt.backgroundColor = [UIColor greenColor];
    [detailview addSubview:detailjumpbt];
    [detailjumpbt addTarget:self action:@selector(detailjumpbt) forControlEvents:UIControlEventTouchUpInside];
    [detailjumpbt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(detailview);
      
        
    }];
    

    
    
#pragma mark - 单人模式和助手模式添加背景  区分手表和画板
  
    UIImageView *modebackground = [[UIImageView alloc] init];
//    modebackground.backgroundColor = [UIColor greenColor];
    modebackground.userInteractionEnabled = YES;
    [bjview addSubview:modebackground];
    _modebackground = modebackground;
    [modebackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(linebottom.mas_bottom).offset(0);
    }];
  
//    mainstring
    UIImageView *mainstring = [[UIImageView alloc] init];
    mainstring.image = [UIImage imageNamed:@"mainstring"];
    [modebackground addSubview:mainstring];
    [mainstring mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bjview.mas_centerX);
        make.width.mas_equalTo(0.8);
        make.height.mas_equalTo(71);
        make.bottom.mas_equalTo(-59);
    }];
    
//    solomode
    UIImageView *solomodeview = [[UIImageView alloc] init];
    solomodeview.image = [UIImage imageNamed:@"solomode"];
    solomodeview.userInteractionEnabled = YES;
    [modebackground addSubview:solomodeview];
    [solomodeview mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(bjview.bounds.size.width/16);
        make.right.mas_equalTo(mainstring.mas_left).offset(-30);
        make.width.mas_equalTo(94);
        make.height.mas_equalTo(77);
        make.bottom.mas_equalTo(-59);
    }];
    
    UIButton *solomodebt = [UIButton buttonWithType:UIButtonTypeSystem];
//    solomodebt.backgroundColor = [UIColor greenColor];
    [solomodeview addSubview:solomodebt];
    _solomodebt = solomodebt;
    [_solomodebt addTarget:self action:@selector(solomodebt) forControlEvents:UIControlEventTouchUpInside];
    [solomodebt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.width.mas_equalTo(94);
        make.height.mas_equalTo(77);
        
    }];
    
    
    
    
//    helpermode
    UIImageView *helpermodeview = [[UIImageView alloc] init];
    helpermodeview.image = [UIImage imageNamed:@"helpermode"];
    helpermodeview.userInteractionEnabled = YES;
    [modebackground addSubview:helpermodeview];
    [helpermodeview mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(bjview.bounds.size.width/4);
        make.left.mas_equalTo(mainstring.mas_right).offset(30);
        make.width.mas_equalTo(102);
        make.height.mas_equalTo(77);
        make.bottom.mas_equalTo(-59);
    }];
    
    UIButton *helpermodebt = [UIButton buttonWithType:UIButtonTypeSystem];
//    helpermodebt.backgroundColor = [UIColor greenColor];
    [helpermodeview addSubview:helpermodebt];
    [helpermodebt addTarget:self action:@selector(helpermodebt) forControlEvents:UIControlEventTouchUpInside];
    [helpermodebt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.width.mas_equalTo(102);
        make.height.mas_equalTo(77);
        
    }];
    
//    artboardmodeview 画板的模式
    
    UIImageView *artboardmodeview = [[UIImageView alloc] init];
    artboardmodeview.image = [UIImage imageNamed:@"solomode"];
    artboardmodeview.userInteractionEnabled = YES;
    [bjview addSubview:artboardmodeview];
    _artboardmodeview = artboardmodeview;
    [artboardmodeview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(bjview);
        make.width.mas_equalTo(94);
        make.height.mas_equalTo(77);
        make.bottom.mas_equalTo(-59);
    }];
    
    UIButton *artboardmodebt = [UIButton buttonWithType:UIButtonTypeSystem];
//    helpermodebt.backgroundColor = [UIColor greenColor];
    [artboardmodeview addSubview:artboardmodebt];
    [artboardmodebt addTarget:self action:@selector(artboardmodebt) forControlEvents:UIControlEventTouchUpInside];
    [artboardmodebt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.width.mas_equalTo(94);
        make.height.mas_equalTo(77);
        
    }];
    
    
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _imgView.frame = self.bounds;
    _bjview.frame = self.bounds;
    _test.frame = CGRectMake(50, 50, 80, 30);
    _linklogo.image = [UIImage imageNamed:[NSString stringWithFormat:@"linklogo%d",_dissindex]];//设备链接标识
    


    
}
- (void)dianliang{
    NSLog(@"电量：self.model.isopen %@",self.model.isopen);
    if([self.model.isopen isEqualToString:@"NO"]){
        return;
    }
    
//    获取电量
    Byte send[] = {0x58,0x57,0x03,0x0B,0x00,0x00,0x00,0x01};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray];
    
    NSString *UUID = [NSString stringWithFormat:@"%@",dict[@"uuid"]] ;
//    [self.blueToothManager writeDatatow:sendData uuid:UUID];
    [self.blueToothManager writeData:sendData];
    
    
    //    链接
    WeakSelf
    self.blueToothManager.datastrBlock = ^(NSString * _Nonnull datastr) {
        NSLog(@"datastr:%@",datastr);
        NSArray *Arr = [NSArray array];
        Arr = [datastr componentsSeparatedByString:@"0x585703"];
        NSLog(@"componentsSeparatedByString========%@",Arr);
        NSString *results2 = [Arr[1] substringToIndex:2];
        NSLog(@"results2:%@",results2);
        int dinal = [XHbluetoolUtils hexadecimalto10:results2];
        NSLog(@"dinal :%d",dinal);
//        电量：0-100
        if(dinal >= 0&& dinal<=20){
            weakSelf.batterystatus.image = [UIImage imageNamed:@"batterystatus0"];
        }
        if(dinal >20 && dinal<=40){
            weakSelf.batterystatus.image = [UIImage imageNamed:@"batterystatus1"];
        }
        if(dinal >40 && dinal<=60){
            weakSelf.batterystatus.image = [UIImage imageNamed:@"batterystatus2"];
        }
        if(dinal >60 && dinal<=80){
            weakSelf.batterystatus.image = [UIImage imageNamed:@"batterystatus3"];
        }
        if(dinal >80 && dinal< 100){
            weakSelf.batterystatus.image = [UIImage imageNamed:@"batterystatus"];
        }
    };
}

- (void)huoqushijian{

}
- (void)bluetoothTime{
    
}
- (void)editStatusbt{
    
    NSLog(@"打开编辑状态");
    [self.textView becomeFirstResponder];

}
- (void)solomodebt{
    NSLog(@"选中的下标 %d",_dissindex);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"solodemo" object:nil userInfo:nil];

}
- (void)helpermodebt{
    NSLog(@"助手模式点击了2");
    [[NSNotificationCenter defaultCenter]postNotificationName:@"helprdemo" object:nil userInfo:nil];
}
- (void)tutoriajumpbt {
    NSLog(@"跳转到教程界面2");
    [[NSNotificationCenter defaultCenter]postNotificationName:@"tutoriademo" object:nil userInfo:nil];
}
- (void)detailjumpbt{
    NSLog(@"跳转到detail界面2");
    NSString *index = [NSString stringWithFormat:@"%ld",_dissindex];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"detaildemo" object:nil userInfo:@{@"index":index}];
}
- (void)resetjumpbt{
    NSLog(@"跳转到reset界面2");
    
//    手表刷新
    if([_realtime.text isEqual:@""]){
        NSLog(@"_realtime.text");
        return;
    }
    
    
    
    
    
    
    
    
    //从字符d中分隔成2个元素的数组
    NSArray *array = [_realtime.text componentsSeparatedByString:@":"];
    NSString * time = [NSString stringWithFormat:@"%@",array[0]];
    NSString * hour = [NSString stringWithFormat:@"%@",array[1]];
    int data = time.intValue;
    int tow = hour.intValue;
    
    NSLog(@"%d",data);
    if(data>12){
        data = data - 12;
    }
    data = [XHbluetoolUtils intTransitionhex16:data];
    tow = [XHbluetoolUtils intTransitionhex16:tow];
    Byte send[] = {0x58,0x57,0x03,0xff,0x00,data,tow,0x01};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];

    NSLog(@"");
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray];
    
    NSString *UUID = [NSString stringWithFormat:@"%@",dict[@"uuid"]] ;
    if([self.model.isopen isEqualToString:@"NO"]){
        NSLog(@"self.model.isopen no");
        
    }else{
//        [self.blueToothManager writeDatatow:sendData uuid:UUID];
        [self.blueToothManager writeData:sendData];
    }
//    [self.blueToothManager writeDatatow:sendData uuid:UUID];
    

    
    if(data<10){
        time = [NSString stringWithFormat:@"0%d",data];
    }else{
        time = [NSString stringWithFormat:@"%d",data];
    }
    if(tow <10){
        hour = [NSString stringWithFormat:@"0%d",tow];
    }else{
        hour = [NSString stringWithFormat:@"%d",tow];
    }
    NSString *timelbz = [NSString  stringWithFormat:@"%@:%@",time,hour];
    
    _timelb.text = timelbz;
    _realtime.text = @"";
    self.isxianshi = NO;
    
    
    
    //    存入蓝牙时间
    [[NSUserDefaults standardUserDefaults] setObject:_timelb.text forKey:@"Bluetoothtime"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    NSLog(@"_timelb.text :%@",_timelb.text);
    
    [self.newtimer invalidate];//先释放
    self.newtimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(dongtai) userInfo:nil repeats:YES];
   //手写代码，加入runLoop
    [[NSRunLoop mainRunLoop] addTimer:self.newtimer forMode:NSDefaultRunLoopMode];
  
    
}
- (void)dongtai{
    NSLog(@"更新的时间:%@",self.realtime.text);
    
    //从字符d中分隔成2个元素的数组
    NSArray *array = [_realtime.text componentsSeparatedByString:@":"];
    NSString * time = [NSString stringWithFormat:@"%@",array[0]];
    NSString * hour = [NSString stringWithFormat:@"%@",array[1]];
    int data = time.intValue;
    int tow = hour.intValue;
    
    NSLog(@"%d",data);
    if(data>12){
        data = data - 12;
    }
    data = [XHbluetoolUtils intTransitionhex16:data];
    tow = [XHbluetoolUtils intTransitionhex16:tow];
    Byte send[] = {0x58,0x57,0x03,0xff,0x00,data,tow,0x01};
    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
#pragma mark - 此版本先不发送
//    [self.blueToothManager writeData:sendData];
    
    if(data<10){
        time = [NSString stringWithFormat:@"0%d",data];
    }else{
        time = [NSString stringWithFormat:@"%d",data];
    }
    if(tow <10){
        hour = [NSString stringWithFormat:@"0%d",tow];
    }else{
        hour = [NSString stringWithFormat:@"%d",tow];
    }
    NSString *timelbz = [NSString  stringWithFormat:@"%@:%@",time,hour];
    
    _timelb.text = timelbz;
    //    存入蓝牙时间
    [[NSUserDefaults standardUserDefaults] setObject:_timelb.text forKey:@"Bluetoothtime"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
- (void)bluetoothTime:(NSNotification *)notification{
    NSLog(@"新的时间出来了");
    NSLog(@"notification %@",notification);
    
    [self.newtimer invalidate];//先释放
    NSDictionary *userInfo = notification.userInfo;
    _timelb.text = [userInfo objectForKey:@"time"];
}
- (void)erasejumpbt{
    NSLog(@"跳转到erase界面2");
}
- (void)artboardmodebt{
    NSLog(@"点击了画板模式的单人模式2");
}
- (void)setDissindex:(NSInteger)dissindex{
    _dissindex = dissindex;

    
}
-(void)setModel:(HXBluetoothConnectionDataModel *)model{
    _model = model;
    NSLog(@"下标:%ld",self.dissindex);
    NSLog(@"self.isopen :%@",model.isopen);
    
    if([model.isopen isEqualToString:@"NO"]){
        //说明还需不显示 数据填充
        [self dianliang];
        self.textView.text = @"magic";
        self.textViewname = @"magic";
        _timelb.hidden = NO;
        _strokesview.hidden = YES;
        if(self.isxianshi){
            _realtime.hidden = NO;
        }
        
        _deviceiconview.hidden = NO;
        _modebackground.hidden = NO;
        
        _eraseview.hidden = YES;
        _resetview.hidden = NO;
        _brushview.hidden = YES;
        _artboardmodeview.hidden = YES;
        
        
        
    }else{
        
   
    
    
    NSLog(@"modelname:%@ electricquantity:%d model.RSSI:%d",model.kCBAdvDataLocalName,model.electricquantity,model.RSSI);
//    _equipmentname.text = [NSString stringWithFormat:@"%@",model.kCBAdvDataLocalName];
    
    self.textView.text = [NSString stringWithFormat:@"%@",FC_SafeString(model.kCBAdvDataLocalName) ];
    self.textViewname = [NSString stringWithFormat:@"%@",FC_SafeString(model.kCBAdvDataLocalName)];
    
    
    [self dianliang];
    
#pragma make     假设是6E400001-B5A3-F393-E0A9-E50E24DCCA9E 是手表，不然是笔画 显示笔画
    if(![model.kCBAdvDataServiceUUIDs isEqualToString:@"6E400001-B5A3-F393-E0A9-E50E24DCCA9E"] ){
        NSLog(@"strokesview 隐藏了2");
        _timelb.hidden = YES;
        _resetview.hidden = YES;
        _realtime.hidden = YES;
        _deviceiconview.hidden = YES;
        _modebackground.hidden = YES;
        
        _strokesview.hidden = NO;
        _eraseview.hidden = NO;
        _brushview.hidden = NO;
        _artboardmodeview.hidden = NO;
       
    }else{
//        NSLog(@"strokesview 隐藏了3");
        _timelb.hidden = NO;
        _strokesview.hidden = YES;
        if(self.isxianshi){
            _realtime.hidden = NO;
        }
        
        _deviceiconview.hidden = NO;
        _modebackground.hidden = NO;
        
        _eraseview.hidden = YES;
        _resetview.hidden = NO;
        _brushview.hidden = YES;
        _artboardmodeview.hidden = YES;
       
    }
        
    }
    
}
- (void)gaintime{
    if(!self.isxianshi){
        _realtime.hidden = YES;
    }
    NSDate *timeDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm"];
    NSString *locationString = [dateFormatter stringFromDate:timeDate];
//    NSLog(@"timeDate:%@",locationString);
    _realtime.text = locationString;
    
//    NSDate *timeDatetwo = [NSDate date];
//    NSCalendar *cal = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *conponent = [cal components:unitFlags fromDate:timeDatetwo];
//    NSInteger year = [conponent year];
//    NSInteger month = [conponent month];
//    NSInteger day = [conponent day];
//    NSInteger hour = [conponent hour];
//    NSInteger min = [conponent minute];
//    NSInteger sec = [conponent second];
//    NSString *nsDateString= [NSString stringWithFormat:@"%4ld-%2ld-%2ld %2ld:%2ld:%2ld", year, month, day,hour, min, sec];
//    NSLog(@"nsDateString:%@",nsDateString);
}
- (void)changelanguages{
    if([themeColors isEqualToString:@"default"]){
        self.contentView.backgroundColor = [UIColor blackColor];
        self.bjview.image = [UIImage imageNamed:@"linkbackground"];
        self.bjview.backgroundColor = [UIColor blackColor];
        self.textView.backgroundColor = [UIColor blackColor];
    }else{
        self.contentView.backgroundColor = midnightRGB;
        self.bjview.image = [UIImage imageNamed:@""];
        self.bjview.backgroundColor = midnightRGB;
        self.textView.backgroundColor = midnightRGB;
    }
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    NSLog(@"将要开始编辑？");
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    NSLog(@"将要结束编辑？");
    
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
    NSLog(@"开始编辑。");
//    self.placeholderLabel.text = @"";
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    NSLog(@"结束编辑。");
    NSLog(@"%@",textView.text);
    
    if(textView.text.length >10){
        [SVProgressHUD showSuccessWithStatus:@"Maximum 10 lengths"];
        textView.text = self.textViewname;
        
        return;
    }
    
    NSString *strdata = [NSString stringWithFormat:@":%@",textView.text];
    NSLog(@"strdata :%@",strdata);
    NSData *testData = [strdata dataUsingEncoding: NSUTF8StringEncoding];//字符串转化成 data
    Byte*testByte = (Byte*)[testData bytes];
    uint8_t*bytes =malloc(sizeof(*bytes)*testData.length);
    for(int i=0;i < [testData length];i++){
//        NSLog(@"myByte = %d\n",testByte[i]);
        bytes[i] = testByte[i];
    }
    NSData*adata = [[NSData alloc]initWithBytes:bytes length:testData.length];
    NSLog(@"adata :%@",adata);
    
    NSLog(@"self.lbdataarray :%@",self.lbdataarray);
    NSDictionary *dict = [NSDictionary dictionaryWithDictionary:self.lbdataarray];
    
    NSString *UUID = [NSString stringWithFormat:@"%@",dict[@"uuid"]] ;
    
    if([self.model.isopen isEqualToString:@"NO"]){
        NSLog(@"self.model.isopen no");
        
    }else{
//        [self.blueToothManager writeDatatow:adata uuid:UUID];
        [self.blueToothManager writeData:adata];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"textViewname" object:nil userInfo:@{@"textViewname":textView.text}];
    }
//    [self.blueToothManager writeData:adata];
    
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"textViewname" object:nil userInfo:@{@"textViewname":textView.text}];
    

}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSLog(@"将要改变内容？");
    
    if([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
        
    }


    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{
    NSLog(@"改变内容。");
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    NSLog(@"选中内容。");
}

//#pragma mark- 按钮点击事件实现方法
//- (void)btnClick:(UIButton*)sender{
//    NSLog(@"添加内容：你好，我好，大家好！");
//
//    self.textView.text = [self.textView.text stringByAppendingString:@"你好，我好，大家好！\n"];
//
//    NSRange range = NSMakeRange([self.textView.text length]- 1, 1);
//    [self.textView scrollRangeToVisible:range];
//
//    [self.contentView endEditing:YES];
//}

/*
 **监听点击事件，当点击非textfiled位置的时候，所有输入法全部收缩
 */
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.contentView endEditing:YES];
}
- (void)selectsendtous{
    NSLog(@"点击了selectsendtous");
    self.textView.text = @"";
}

-(NSData *)nsdataFromHexString:(NSString *)hexString{
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
    NSMutableData* data = [NSMutableData data];

    while (*ch) {
        if (*ch == ' ') {
            continue;
        }
        char byte = 0;
        if ('0' <= *ch && *ch <= '9') {
            byte = *ch - '0';
        }

        else if ('a' <= *ch && *ch <= 'f') {
            byte = *ch - 'a' + 10;
        }

        else if ('A' <= *ch && *ch <= 'F') {
            byte = *ch - 'A' + 10;
        }
        ch++;
        byte = byte << 4;
        if (*ch) {
            if ('0' <= *ch && *ch <= '9') {
                byte += *ch - '0';
            } else if ('a' <= *ch && *ch <= 'f') {
                byte += *ch - 'a' + 10;
            }

            else if('A' <= *ch && *ch <= 'F')
            {
                byte += *ch - 'A' + 10;
            }
            ch++;
        }
        [data appendBytes:&byte length:1];
    }
    return data;
}
- (int) intFromDataReverse:(NSData *)data
{
    int intSize = sizeof(int);// change it to fixe length
    unsigned char * buffer = malloc(intSize * sizeof(unsigned char));
    [data getBytes:buffer length:intSize];
    int num = 0;
    for (int i = intSize - 1; i >= 0; i--) {
        num = (num << 8) + buffer[i];
    }
    free(buffer);
    return num;
}
// 将字符串转为16进制
- (NSString *)hexStringFromString:(NSString *)string {
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"%@",myD);
    Byte *bytes = (Byte *)[myD bytes];
 
    //下面是Byte 转换为16进制。
    NSString *hexStr = @"";
    for(int i = 0; i < [myD length]; i++) {
//        NSLog(@"%x",bytes[i]);
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff]; //16进制数
        if([newHexStr length] == 1) {
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        } else {
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
    }
    int num = hexStr.length % 16;
    if (num == 0) {
 
    } else {
        for (int i = 0; i < 16 - num; i++) {
            hexStr = [NSString stringWithFormat:@"%@F",hexStr];
        }
    }
    return hexStr;
}
- (void)lastTimeOfThedevice{
//    //    获取最后的时间
//    Byte send[] = {0x58,0x57,0x03,0x0B,0x00,0x00,0x00,0x01};
//    NSData *sendData = [NSData dataWithBytes:&send length:sizeof(send)];
//    [self.blueToothManager writeData:sendData];
//
//    NSLog(@"blueToothManager: %@",self.blueToothManager);
//    //    链接
//    WeakSelf
//    self.blueToothManager.datastrBlock = ^(NSString * _Nonnull datastr) {
//        NSLog(@"datastr：：： %@",datastr);
//    };
}
@end
